﻿using System;
using System.Collections.Generic;
using Apache.Cassandra;

namespace Sandy
{
    public class Range
    {
        public string First;
        public string Last;
        public int Count;
        public bool Reversed;
        
        private bool _isPrefix = false;

        public static Range AllInclusive
        {
            get
            {
                return new Range(count: int.MaxValue);
            }
        }
        
        public Range(string first = "", string last = "", int count = 100, bool reversed = false)
        {
            First = first;
            Last = last;
            Count = count;
            Reversed = reversed;
        }

        internal SliceRange ToSliceRange(SandyFamily family)
        {
            var sr = new SliceRange
                       {
                           Start = family.ColumnNameToBytes(First),
                           Finish = family.ColumnNameToBytes(Last),
                           Count = Count,
                           Reversed = Reversed
                       };

            if (_isPrefix)
            {
                // We need to put in Last the 
                switch (family.ColumnType)
                {
                    case ColumnType.AsciiType:
                        sr.Finish = family.ColumnNameToBytes(First + '\x7f');
                        break;
                    case ColumnType.Utf8Type:
                        sr.Finish = family.ColumnNameToBytes(First + '\xff');
                        break;
                    default:
                        throw new ArgumentOutOfRangeException("Can only use Ascii or UTF8 type for StartsWith");
                }
            }

            return sr;
        }

        public SliceRange ToSuperSliceRange(SandyFamily family)
        {
            return new SliceRange
            {
                Start = family.SuperColumnNameToBytes(First),
                Finish = family.SuperColumnNameToBytes(Last),
                Count = Count,
                Reversed = Reversed
            };
            
        }

        public static Range StartsWith(string prefix)
        {
            return new Range(prefix) {_isPrefix = true};
        }
    }
}